import axios from 'axios'
import { baseURL } from '@/config/index'
import ViewUI from 'view-design'
axios.defaults.baseURL = baseURL
class HttpRequest {
  constructor () {
    this.timeout = 10000
    this.withCredentials = true
  }

  getInsideConfig () {
    const config = {
      timeout: this.timeout,
      withCredentials: this.withCredentials
    }
    return config
  }

  request(options) {
    const instance = axios.create()
    const config = Object.assign(options, this.getInsideConfig())
    this.setInterceptors(instance, options.url)
    return instance(config)
  }

  setInterceptors(instance, url) {
    instance.interceptors.request.use(config => {
      ViewUI.LoadingBar.start()
      // request.headers.AuthorizationToken = localStorage.getItem('AuthorizationToken') || ''
      // 添加全局的loading
      return config
    }, err => Promise.reject(err))
    instance.interceptors.response.use(response => {
      ViewUI.LoadingBar.finish()
      return response
    }, err => {
      if (err.response) { // 响应错误码处理
        switch (err.response.status) {
          case '403':
            // todo: handler server forbidden error
            break
            // todo: handler other status code
          default:
            break
        }
        return Promise.reject(err.response)
      }
      if (!window.navigator.online) { // 断网处理
        // todo: jump to offline page
        return -1
      }
      return Promise.reject(err)
    })
  }
}

export default HttpRequest
